package com.huizhonglm.diap.core.upload;

import android.os.Handler;
import android.os.Message;

import com.huizhonglm.diap.core.utils.LogUtil;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * 上传工具类
 *
 * @author LiXiaolong
 * 支持上传文件和参数
 */

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-05-31 09:42
 */
public class Upload {
    private static Upload mInstance;

    private final String TAG = "DIAP_API";
    private final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    private final String PREFIX = "--";
    private final String LINE_END = "\r\n";
    private final String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    private final String CHARSET = "utf-8"; // 设置编码

    private final int MSG_WHAT_SUCCESS = 11;
    private final int MSG_WHAT_NOT_EXISTS = 22;
    private final int MSG_WHAT_ERROR = 33;

    private final int UPLOAD_SUCCESS_CODE = 1;// 上传成功
    private final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;// 文件不存在
    private final int UPLOAD_SERVER_ERROR_CODE = 3;// 服务器出错



    private UploadCallback uploadCallback;

    private UploadHandler uploadHandler;

    /**
     * 单例模式获取上传工具类
     * @return UploadUtil
     */
    public static Upload getInstance() {
        if (mInstance == null) {
            synchronized (Upload.class) {
                if (mInstance == null) {
                    mInstance = new Upload();
                }
            }
        }
        return mInstance;
    }

    private Upload() {
        uploadHandler = new UploadHandler(this);
    }


    /**
     * android上传文件到服务器
     *
     * @param filePath
     * 需要上传的文件的路径
     * @param fileKey
     * 在网页上<input type=file name=xxx/> xxx就是这里的fileKey
     * @param url
     * 请求的URL
     */
    public void toUpload(String filePath, String fileKey, String url, Map<String, String> param, UploadCallback cbk) {
        this.uploadCallback = cbk;
        if (filePath == null) {
            sendMessage(MSG_WHAT_NOT_EXISTS, "文件不存在");
            return;
        }
        try {
            File file = new File(filePath);
            uploadFile(file, fileKey, url, param);
        } catch (Exception e) {
            sendMessage(MSG_WHAT_NOT_EXISTS, "文件不存在");
            e.printStackTrace();
        }
    }

    /**
     * android上传文件到服务器
     *
     * @param file
     * 需要上传的文件
     * @param fileKey
     * 在网页上<input type=file name=xxx/> xxx就是这里的fileKey
     * @param url
     * 请求的URL
     */
    private void uploadFile(final File file, final String fileKey, final String url, final Map<String, String> param) {
        if (file == null || (!file.exists())) {
            sendMessage(MSG_WHAT_NOT_EXISTS, "文件不存在");
            return;
        }
        LogUtil.print(TAG, "请求的URL=" + url);
        LogUtil.print(TAG, "请求的fileName=" + file.getName());
        LogUtil.print(TAG, "请求的fileKey=" + fileKey);
        new Thread(new Runnable() { //开启线程上传文件
            @Override
            public void run() {
                doUpload(file, fileKey, url, param);
            }
        }).start();

    }

    private void doUpload(File file, String fileKey, String reqUrl, Map<String, String> param) {
        String result;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            /**
             * 当文件不为空，把文件包装并且上传
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuilder sb;
            String params;

            /***
             * 以下是用于上传参数
             */
            if (param != null && param.size() > 0) {
                Iterator<String> it = param.keySet().iterator();
                while (it.hasNext()) {
                    sb = new StringBuilder();
                    String key = it.next();
                    String value = param.get(key);
                    sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
                    sb.append(value).append(LINE_END);
                    params = sb.toString();
                    LogUtil.print(TAG, key + "=" + params + "##");
                    dos.write(params.getBytes());
                    // dos.flush();
                }
            }

            sb = new StringBuilder();
            /**
             * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
             * filename是文件的名字，包含后缀名的 比如:abc.png
             */
            sb.append(PREFIX)
                    .append(BOUNDARY)
                    .append(LINE_END);
            sb.append("Content-Disposition:form-data; name=\"")
                    .append(fileKey)
                    .append("\"; filename=\"")
                    .append(file.getName())
                    .append("\"")
                    .append(LINE_END);
            sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ，用于服务器端辨别文件的类型的
            sb.append(LINE_END);
            params = sb.toString();

            LogUtil.print(TAG, file.getName() + "=" + params + "##");
            dos.write(params.getBytes());
            /**上传文件*/
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();

            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            //
            // dos.write(tempOutputStream.toByteArray());
            /**
             * 获取响应码 200=成功 当响应成功，获取响应的流
             */
            int resCode = conn.getResponseCode();
            LogUtil.print(TAG, "response code:" + resCode);
            if (resCode == 200) {
                LogUtil.print(TAG, "request success");
                InputStream input = conn.getInputStream();
                StringBuilder sb1 = new StringBuilder();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
                LogUtil.print(TAG, "result : " + result);
                sendMessage(MSG_WHAT_SUCCESS, result);
            } else {
                LogUtil.print(TAG, "上传失败：responseCode=" + resCode);
                sendMessage(MSG_WHAT_ERROR, "上传失败，服务器异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendMessage(MSG_WHAT_ERROR, "上传失败，服务器异常");
        }
    }

    private void sendMessage(int what, String result){
        Message msg = new Message();
        msg.what = what;
        msg.obj = result;
        uploadHandler.sendMessage(msg);
    }

    private void handleMessage(Message msg) {
        String result = (String) msg.obj;
        switch (msg.what) {
            case MSG_WHAT_SUCCESS:
                handleCallback(UPLOAD_SUCCESS_CODE, result);
                break;
            case MSG_WHAT_NOT_EXISTS:
                handleCallback(UPLOAD_FILE_NOT_EXISTS_CODE, result);
                break;
            case MSG_WHAT_ERROR:
                handleCallback(UPLOAD_SERVER_ERROR_CODE, result);
                break;
        }
    }

    private void handleCallback(int resCode, String result){
        if (uploadCallback != null) {
            if (resCode == UPLOAD_SUCCESS_CODE) {
                uploadCallback.onUploadSuccess(result);
            } else {
                uploadCallback.onUploadFailure(result);
            }
        }
    }

    public static class UploadHandler extends Handler {
        WeakReference<Upload> wrf;

        public UploadHandler(Upload cls) {
            wrf = new WeakReference<>(cls);
        }

        @Override
        public void handleMessage(Message msg) {
            Upload upload = wrf.get();
            if (upload != null) {
                upload.handleMessage(msg);
            }
        }
    }
}
